package com.perkinelmer.housecall.client.activity;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.ui.Panel;
import com.perkinelmer.housecall.client.activity.Activity.ActivityId;

public class ActivityManager {

	private final Map<ActivityId<?>, Activity<?>> activityMap = new HashMap<ActivityId<?>, Activity<?>>();
	private final Panel activityPanel;
	
	private Activity<?> currentActivity = null;
	
	public ActivityManager(Panel panel) {
		this.activityPanel = panel;
	}

	public void setLibrary(ActivityLibrary library) {
		activityMap.clear();
		for(Activity<?> activity : library.getActivities()) {
			activityMap.put(activity.getId(), activity);
		}
	}
	
	public <P> void gotoActivity(ActivityId<P> id, P parameters) {
		if(currentActivity != null) {currentActivity.stop();}
		activityPanel.clear();
		
		Activity<P> activity = getActivity(id);
		activity.start(activityPanel, parameters);
		currentActivity = activity;
	}
	
	public void gotoActivity(ActivityId<NoParameters> id) {
		if(currentActivity != null) {currentActivity.stop();}
		activityPanel.clear();
		
		NoParameterActivity activity = (NoParameterActivity)getActivity(id);
		activity.start(activityPanel);
	}
	
	@SuppressWarnings("unchecked")
	private <P> Activity<P> getActivity(ActivityId<P> id) {
		return (Activity<P>)activityMap.get(id);
	}
}
